package preference

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"sync"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type Preference struct {
	UseFakeGameDirectory bool
	IsDarkMode           bool
	PlayerName           string
	DefaultGameDirectory string
	DefaultJavaDirectory string

	ctx context.Context
	mut sync.Mutex
}

func NewPreference() *Preference {
	p := &Preference{
		UseFakeGameDirectory: false,
		IsDarkMode:           false,
		PlayerName:           "Steve",
		DefaultGameDirectory: ".minecraft",
		DefaultJavaDirectory: "java is not found",
	}

	p.LoadFromLocal()

	return p
}

func (p *Preference) SetContext(ctx context.Context) {
	p.ctx = ctx
}

func (p *Preference) LoadFromLocal() {
	if _, err := os.Stat(".sf/"); err != nil {
		return
	}

	jsonData, err := os.ReadFile(".sf/preference.json")

	if err != nil {
		return
	}

	p.mut.Lock()
	defer p.mut.Unlock()

	json.Unmarshal(jsonData, p)
}

func (p *Preference) SaveToLocal() {
	if _, err := os.Stat(".sf/"); err != nil {
		err = os.MkdirAll(".sf/", os.ModePerm)

		if err != nil {
			fmt.Println(err)

			return
		}
	}

	p.mut.Lock()

	jsonData, err := json.Marshal(p)

	p.mut.Unlock()

	if err != nil {
		return
	}

	os.WriteFile(".sf/preference.json", jsonData, 0644)
}

func (p *Preference) SetUseFakeGameDirectory(use bool) {
	p.mut.Lock()
	defer p.mut.Unlock()

	p.UseFakeGameDirectory = use
}

func (p *Preference) GetUseFakeGameDirectory() bool {
	p.mut.Lock()
	defer p.mut.Unlock()

	return p.UseFakeGameDirectory
}

func (p *Preference) SetIsDarkMode(isDMode bool) {
	p.mut.Lock()
	defer p.mut.Unlock()

	p.IsDarkMode = isDMode
}

func (p *Preference) GetIsDarkMode() bool {
	p.mut.Lock()
	defer p.mut.Unlock()

	return p.IsDarkMode
}

func (p *Preference) SetPlayerName(name string) {
	p.mut.Lock()
	defer p.mut.Unlock()

	p.PlayerName = name
}

func (p *Preference) GetPlayerName() string {
	p.mut.Lock()
	defer p.mut.Unlock()

	return p.PlayerName
}

func (p *Preference) SetDefaultGameDirectory() string {
	gameDir, err := runtime.OpenDirectoryDialog(p.ctx, runtime.OpenDialogOptions{})

	if err != nil {
		return p.DefaultGameDirectory
	}

	if gameDir == "" {
		return p.DefaultGameDirectory
	}

	p.mut.Lock()
	defer p.mut.Unlock()

	p.DefaultGameDirectory = gameDir

	return p.DefaultGameDirectory
}

func (p *Preference) GetDefaultGameDirectory() string {
	p.mut.Lock()
	defer p.mut.Unlock()

	return p.DefaultGameDirectory
}

func (p *Preference) SetDefaultJavaDirectory() string {
	javaDir, err := runtime.OpenDirectoryDialog(p.ctx, runtime.OpenDialogOptions{})

	if err != nil {
		return p.DefaultJavaDirectory
	}

	if javaDir == "" {
		return p.DefaultJavaDirectory
	}

	p.mut.Lock()
	defer p.mut.Unlock()

	p.DefaultJavaDirectory = javaDir

	return p.DefaultJavaDirectory
}

func (p *Preference) GetDefaultJavaDirectory() string {
	p.mut.Lock()
	defer p.mut.Unlock()

	return p.DefaultJavaDirectory
}
